<template>
	<el-dialog :visible.sync="isShow" @close="close" width="70%" class="hechaDialog" :show-close='false' :closeOnClickModal='false'
	 append-to-body>
		<span slot="title" class="dialog-title">
		  	<span style = "font-size:13px;margin-right:8px;">期间核查</span>  {{periodCheckRecordData.name}}
			<el-button  size="mini" @click="close" class="popupClose">关闭</el-button>
		</span>
		<el-form label-width="110px" :inline="false" class="demo-form-inline hechaForm" :model="uploadData" :rules="hechaRules" ref="jiandingForm">
			<el-form-item label="核查人" prop='executor'>
				<el-col :span="22">
					<el-select filterable multiple v-model="uploadData.executor" placeholder="请选择" size='mini' disabled style="width:100%;">
						<el-option v-for="item in EmployeeByLabs" :key="item.account" :label="item.name" :value="item.account" :disabled="item.disabled">

						</el-option>
					</el-select>
				</el-col>
			</el-form-item>
			<el-form-item label="核查日期" prop='executeDate'>
				<el-col :span="22">
					<el-date-picker size="mini" style="width:100%;" v-model="uploadData.executeDate" type="date" placeholder="默认当前日期" value-format="yyyy-MM-dd" :disabled="flag != 'new' && flag != 'edit'">
					</el-date-picker>
				</el-col>
			</el-form-item>
			<el-form-item label="审核人" prop='assignercode'>
				<el-col :span="22">
					<el-select filterable v-model="uploadData.assignercode" style="width:100%;" placeholder="请选择" size='mini' :disabled="flag != 'new' && flag != 'edit' ">
						<el-option v-for="item in EmployeeByLabs" :key="item.account" :label="item.name" :value="item.account"  :disabled="item.disabled">

						</el-option>
					</el-select>
				</el-col>
			</el-form-item>
      <el-form-item label="核查意见" prop='remark' style="width:100%;float:none;">
        <el-col :span="22">
          <el-input type="textarea" size="mini" :disabled="flag == 'look' || flag == 'shenhe'" placeholder="输入期间核查意见"
            v-model="uploadData.remark"></el-input>
        </el-col>
      </el-form-item>
		</el-form>
		<div class="elTab">
			<el-tabs style="width: 100%;" v-model = "activeName">
				<el-tab-pane label="附件" name="first">
					<el-row v-if="(flag=='new' || flag=='edit') && $parent.$parent.userOpernation.upload.display">
						<el-button type="primary" size="mini" @click="hcUpload" style="float:right;margin-bottom:5px;">上传</el-button>
						<input type="file" @change="getFile" multiple="multiple" id="hc-file" style='visibility: hidden;width: 0;height: 0;'>
					</el-row>
					<el-table :data="uploadData.files" style="width: 100%;height:calc(100% - 43px)" size="mini" class="tableCon">
						<el-table-column label="序号" min-width="50px">
							<template slot-scope="scope">
								{{scope.$index+1}}
							</template>
						</el-table-column>
						<el-table-column property="name" label="附件名称" key="file" v-if="flag=='new' || flag=='edit' " min-width="200px" :show-overflow-tooltip="true">
						</el-table-column>
						<el-table-column property="fileName" label="附件名称" key="file1" v-if="flag=='look'||flag=='shenhe'" min-width="200px" :show-overflow-tooltip="true">
						</el-table-column>
						<el-table-column label="操作" min-width="100px">
							<template slot-scope="scope">
								<el-button type="text" size="mini" @click="removeTag(scope.row,scope.$index)" v-if="flag=='new' || flag=='edit'">删除</el-button>
								<el-button type="text" size="mini" @click="downLoadFile(scope.row)" v-if=" (flag=='look'||flag=='shenhe')">下载</el-button>
								<el-button type="text" size="mini" @click="previewFile(scope.row)"  v-if=" (flag=='look'||flag=='shenhe')">预览</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="审核信息" name="second" v-if="flag == 'look' || flag=='shenhe'">
					<div id="myIframe" v-if="reload" v-loading="loading1" style = "text-align:center;">
						 <span style = "color:#909399;line-height:100px;" v-if = "WorkFlowMsg != '' && WorkFlowMsg != undefined" >{{WorkFlowMsg}}</span>
						<iframe :src="url" id="workFlowIframe" ref="workFlowIframe" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>
		<span slot="footer" class="dialog-footer">
			<!---->
			<el-button v-if="flag=='shenhe'" class="penalButton" type="primary" size="mini" v-on:click="reviewFlowPop">审核</el-button>
	  	 	<el-button v-if="flag=='new' || flag=='edit'" class="penalButton" type="primary" size="mini" v-on:click="submitUpload" :disabled = "!isRepeat">确定</el-button>
			<el-button  class="penalButton" size="mini" v-on:click="close">取消</el-button>
	  </span>
	  <review-flow :addVisible.sync="reviewFlowShow" :reviewData="reviewData" :procInstType="procInstType" :reviewTitle="reviewTitle"
		 @reloadMain="readAbility"></review-flow>
	</el-dialog>
</template>

<script>
	import { mapState } from 'vuex'
	const reviewFlow = () => import('@/common/reviewFlow.vue');
	export default {
		data() {
			return {
				isShow: true,
				AuditArr: [],
				reviewFlowShow: false, //审核流显示
				reviewData: null, //点击行需要审核的信息
				procInstType: 't_maintenance_record', //审核流要查的表
				reviewTitle: '期间核查审核',
				totalFile: null,
				yesornoValue: '1',
				enableStatusValue: '1',
				multipleSelection: [],
				kaishiriqi: '',
				jieshuriqi: '',
				xunhuanzhouqiValue: '001',
				xunhuan: '',
				cishu: '',
				jiandingriqi: '',
				uploadData: {
					equipment: this.util.date(),
					maintainType: 'MA03',
					executor: [],
					assignercode: '',
					executeDate: '',
					files: [],
          remark: '',
				},
				hechaRules: {
					assignercode:[{required: true, message:'请填写核查人', trigger:'change' }],
					executeDate:[{required: true, message:'请选择核查日期', trigger:'change' }],
          remark:[{required: true, message:'请填写核查意见', trigger:'blur' }],
				},
				isRepeat:true,
				activeName:"first",
				loading1:true,
				reload:true,
				url:"",
				WorkFlowMsg:"",

			}
		},
		computed: {
			...mapState(['EmployeeByLabs']),
			biaoyangTableHeight() {
				return ((window.innerHeight - 90) * 0.8 - 250)
			}
		},
		props: ['flag', 'eqid', 'detailList','periodCheckRecordData'],
		components: {
			reviewFlow
		},
		created() {
			// this.getEmployeeByEquip()
		},
		watch:{
			activeName(val) {
				if (val == "second") {
				this.reload = true;
				if (process.env.NODE_ENV == 'development') {

					this.url = "../../static/workflow.html?id=" + this.uploadData.id + "&procInstType=" + this.procInstType + "&fromModel=look"

				} else {
					this.url = "static/workflow.html?id=" + this.uploadData.id + "&procInstType=" + this.procInstType + "&fromModel=look"

				}
				var that = this;
				// setTimeout(function () {
					let iframe = document.getElementById("workFlowIframe");
					window.addEventListener('message', that.handleMessage1)
				// }, 3000)
				}
			}
		},
		mounted() {
      console.log(this.detailList)
			if(this.flag == "edit" || this.flag == "new"){
				var assignercode = this.detailList.assignercode;
				if(this.detailList.assignercode == undefined){
					assignercode = '';
				}
				var executeDate = this.detailList.executeDate;
				if(this.detailList.executeDate == undefined){
					executeDate = this.util.date();
				}
				this.$set(this.uploadData, 'executor', this.detailList.executor.split(','))
				this.$set(this.uploadData, 'assignercode', assignercode )
				this.$set(this.uploadData, 'executeDate', executeDate)
				this.$set(this.uploadData, 'id', this.detailList.id)
				this.$set(this.uploadData, 'name', this.detailList.name)
				this.$set(this.uploadData, 'status', this.detailList.status)

				if(this.detailList.status == 4){
					for(var i in this.detailList.files){
						this.detailList.files[i].name = this.detailList.files[i].fileName
					}
					this.$set(this.uploadData, 'files', this.detailList.files)
				}else{
          this.uploadData.remark = "";
        }
         this.$set(this.uploadData, 'remark', this.detailList.remark)
			}
			if(this.flag == "look" || this.flag == "shenhe"){
				this.uploadData = Object.assign({}, this.uploadData, this.detailList);
				this.uploadData.executor = this.detailList.executor.split(',')
				this.uploadData.files = JSON.parse(JSON.stringify(this.uploadData.fileList))
			}

		},
		methods: {
			handleMessage1(event) {
				const data = event.data
				console.log(data)
				switch (data.cmd) {
					case 'loadingHide':
						this.loading1 = false;
					    this.WorkFlowMsg = "";
					break;
				case 'errorMsg':
					this.loading1 = false;
					this.WorkFlowMsg = "没有查询到审核信息"
					break;
				}
			},
			//			获取审核人接口：resource/getEmployeeByEquip.htm，
			getEmployeeByEquip() {
				this.$http({
					apiUrl: 'resource/getEmployeeByEquip.htm',
					method: 'post',
					isJson: false,
					params: { equipment: this.detailList.equipmentId },

				}).then(res => {
					if (res.code === 0) {
						this.AuditArr = res.data
					}
				})
			},
			removeTag(row,index) {
        if (row.hasOwnProperty('id')) {
          this.$confirm('确定要删除已上传的文件吗', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              method: 'post',
              apiUrl: '/download/fileDelete.htm',
              params: {
                id: row.id,
              },
              isJson: false,
            }).then(res => {
              if (res.code === 0) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.uploadData.files.splice(index, 1)
              }
            })
          })
        } else {
          this.uploadData.files.splice(index, 1)
        }
				// this.uploadData.files.splice(index, 1)
			},
			reviewFlowPop() {
				this.reviewFlowShow = true;
				this.reviewData = this.uploadData;
			},
			readAbility() {
				this.reviewFlowShow = false;
				this.$store.dispatch('getWorkflowList', 0).then(res => {
					this.$notify({
						showClose: true,
						message: '操作成功',
						type: 'success',
						title:"成功"
					})
				})
				this.close()
				this.$parent.init();
				this.$parent.$parent.readMaintenanceList()

			},
			downLoadFile(item) {
				var url = "/download/fileDownload.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?id=' + item.id + "&token=" + token);
			},
			// 预览
			previewFile(row){
				var url = "preview/fileToPdfPreview.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
			},
			hcUpload() {
				document.getElementById("hc-file").click()
			},
			submitUpload() {
				this.$refs.jiandingForm.validate((valid) => {
					if(valid){
						this.uploadData.equipment = this.eqid;
						if (this.uploadData.files.length == 0) {
							this.$notify({
								type: "warning",
								title: "警告！",
								message: "请上传文件！"
							})
							return;
						}
						let params = this.formDating(this.uploadData);
						let url;
						if (this.flag == 'new') {
							url = 'resource/createMaintenanceRecord.htm'
						} else if (this.flag = 'edit') {
							url = 'resource/updateMaintenanceRecordHecha.htm'
						}
						this.isRepeat =false;
						this.$http({
							apiUrl: url,
							method: 'post',
							params: params,
							headers: {
                'Content-Type': 'multipart/form-data',
                'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined }
						}).then(res => {
							this.isRepeat =true;
							if (res.code === 0) {
								this.$message({
									showClose: true,
									message: '操作成功！',
									type: 'success'
								})
								this.close()
								this.$parent.init()
								this.$parent.$parent.readMaintenanceList()
							}
						})
					}

				})


			},
			formDating(params) {
				let fromArr = params
				let $formData = new FormData();
				for (let j in fromArr) {
					if ((typeof fromArr[j]) == 'object') {
						for (let i of fromArr[j]) {
							$formData.append(j, i);
						}
					} else {
						$formData.append(j, fromArr[j]);
					}
				}
				return $formData
			},
			getFile($event) {
				//				console.log($event.target.files);
				//				console.log(Array.from($event.target.files))
				let count = 0;
				//				this.uploadData.files = $event.target.files
				for (let i of $event.target.files) {
					count = 0
					for (let j of this.uploadData.files) {
						if (i.name == j.name) {
							count += i.name
						}
					}
					if (count == 0) {
						this.uploadData.files.push(i)
					} else {
						this.$message({
							showClose: 'true',
							message: '重复添加，已过滤！',
							type: 'success'
						})
					}

				}
				this.totalFile = this.uploadData.files.length
				$event.target.value = "";
			},

			close() {
				this.isRepeat =true;
				this.$parent.qjhcjiluShow = false;
				this.activeName = "first";
				this.loading1 = true;
				this.reload = false;
				this.WorkFlowMsg = "";
			}

		}
	}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
	.hechaDialog .el-dialog {
		margin-top: 10vh !important;
		height: 80%;
	}

	.hechaDialog .el-dialog .el-dialog__body {
		height: calc(100% - 85px);
		padding: 15px;
	}

	.hechaDialog .hechaForm {
		height: 160px;
	}

	.hechaDialog .hechaForm .el-form-item {
		margin-bottom: 15px;
	}

	.hechaDialog .el-dialog .elTab {
		clear: both;
		height: calc(100% - 160px)
	}

	.hechaDialog .el-dialog .elTab .el-tabs {
		height: 100%
	}

	.hechaDialog .el-dialog .elTab .el-tabs .el-tabs__content {
		height: calc(100% - 98px)
	}

	.hechaDialog .el-dialog .elTab .el-tabs .el-tabs__content .el-tab-pane {
		height: 100%
	}
</style>
